package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/*
定时任务类：处理超时未支付的订单和一直派送中的订单状态
* */

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    //每分钟检查一次是否存在超时未支付订单
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processOutTimeOrder(){
        log.info("超时订单任务检查");
        LocalDateTime time = LocalDateTime.now().minusMonths(15);
       List<Orders> ordersList= ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
       if(ordersList!=null&&ordersList.size()>0){
           ordersList.forEach(orders->{
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("订单超时");
               orders.setCancelTime(LocalDateTime.now());
               ordersMapper.update(orders);
           });
       }
    }
    //每天凌晨一点检查一次订单表，查看是否存在“派送中”的订单，如果存在修改状态为“已完成”
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveredOrder(){
    LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList!=null&&ordersList.size()>0){
            ordersList.forEach(orders->{
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(time);
                ordersMapper.update(orders);
            });
        }
    }
}
